// popup.js - 处理解锁码输入和界面逻辑

document.addEventListener('DOMContentLoaded', async () => {
  // 生成并显示 logo
  const logoCanvas = document.getElementById('logo-canvas');
  const logoDataUrl = window.logoGenerator.generateLogo(64);
  const img = new Image();
  img.onload = () => {
    const ctx = logoCanvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
  };
  img.src = logoDataUrl;

  // 检查解锁状态
  const unlockSection = document.getElementById('unlock-section');
  const playerSection = document.getElementById('player-section');
  const unlockCodeInput = document.getElementById('unlock-code');
  const unlockBtn = document.getElementById('unlock-btn');
  const openPlayerBtn = document.getElementById('open-player-btn');
  const unlockStatus = document.getElementById('unlock-status');
  const timeRemaining = document.getElementById('time-remaining');

  // 检查存储的解锁状态
  const result = await chrome.storage.local.get(['unlockCode', 'unlockTime', 'isUnlocked']);
  
  if (result.isUnlocked && result.unlockTime) {
    const unlockTime = result.unlockTime;
    const now = Date.now();
    const elapsed = now - unlockTime;
    const remaining = 12 * 60 * 60 * 1000 - elapsed; // 12小时

    if (remaining > 0) {
      // 仍然有效
      showPlayerSection();
      updateTimeRemaining(remaining);
      // 每秒更新一次倒计时
      const timer = setInterval(() => {
        const newRemaining = 12 * 60 * 60 * 1000 - (Date.now() - unlockTime);
        if (newRemaining > 0) {
          updateTimeRemaining(newRemaining);
        } else {
          clearInterval(timer);
          showUnlockSection();
          chrome.storage.local.remove(['unlockCode', 'unlockTime', 'isUnlocked']);
        }
      }, 1000);
    } else {
      // 已过期
      showUnlockSection();
      chrome.storage.local.remove(['unlockCode', 'unlockTime', 'isUnlocked']);
    }
  } else {
    showUnlockSection();
  }

  // 解锁按钮点击事件
  unlockBtn.addEventListener('click', async () => {
    const code = (unlockCodeInput.value || '').trim().split(/[\s,;]+/).filter(Boolean)[0] || '';
    
    if (!code) {
      showStatus('请输入解锁码', 'error');
      return;
    }

    unlockBtn.disabled = true;
    unlockBtn.textContent = '验证中...';

    try {
      // 校验解锁码
      const api = `https://api.flac.life/unlock/${encodeURIComponent(code)}`;
      const res = await fetch(api, { credentials: 'omit', cache: 'no-store' });
      const data = await res.json().catch(() => null);

      if (!data || data.code !== 200) {
        showStatus('解锁失败，请检查解锁码', 'error');
        unlockBtn.disabled = false;
        unlockBtn.textContent = '确认解锁';
        return;
      }

      // 成功：保存参数供后续 unlockcode 使用
      const unlockTime = Date.now();
      await chrome.storage.local.set({
        unlockCode: code,
        unlockTime: unlockTime,
        isUnlocked: true
      });

      // 通知 background（便于后续请求携带 unlockcode）
      chrome.runtime.sendMessage({
        type: 'unlock',
        code: code
      });

      showStatus('解锁成功！', 'success');
      setTimeout(() => {
        showPlayerSection();
        updateTimeRemaining(12 * 60 * 60 * 1000);
        unlockCodeInput.value = '';
      }, 600);
    } catch (_) {
      showStatus('网络异常，请稍后重试', 'error');
      unlockBtn.disabled = false;
      unlockBtn.textContent = '确认解锁';
    }
  });

  // 回车键提交
  unlockCodeInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      unlockBtn.click();
    }
  });

  // 打开播放器按钮
  openPlayerBtn.addEventListener('click', () => {
    chrome.tabs.create({
      url: chrome.runtime.getURL('player.html')
    });
    window.close();
  });

  function showUnlockSection() {
    unlockSection.classList.remove('hidden');
    playerSection.classList.add('hidden');
    unlockBtn.disabled = false;
    unlockBtn.textContent = '确认解锁';
    unlockStatus.textContent = '';
  }

  function showPlayerSection() {
    unlockSection.classList.add('hidden');
    playerSection.classList.remove('hidden');
  }

  function showStatus(message, type) {
    unlockStatus.textContent = message;
    unlockStatus.className = `status-message ${type}`;
  }

  function updateTimeRemaining(ms) {
    const hours = Math.floor(ms / (60 * 60 * 1000));
    const minutes = Math.floor((ms % (60 * 60 * 1000)) / (60 * 1000));
    const seconds = Math.floor((ms % (60 * 1000)) / 1000);
    
    timeRemaining.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }
});

